//
// Created by casdon on 2024/8/1.
//

#ifndef CIOT_SYSTEM_H
#define CIOT_SYSTEM_H

#include "types.h"

#ifdef __cplusplus
extern "C" {
#endif

/**
 * System Adapter
 */
typedef struct ciot_system_adapter_manager_t
{
    bool inited;
    CIOT_ADAPTER    void (* sleep_ms) ( Ciot_time_ms time );

    CIOT_ADAPTER    int  (* printf) ( const char * format, ...);

    CIOT_ADAPTER    void * (*mem_alloc)( size_t size);
    CIOT_ADAPTER    void * (*mem_calloc)( size_t n, size_t size);
    CIOT_ADAPTER    void * (*mem_set)( void *ptr, uint8_t c, size_t len );
    CIOT_ADAPTER    void * (*mem_cpy)( void *ptr, const void * from, size_t len );
    CIOT_ADAPTER    void * (*mem_new)( size_t size);
    CIOT_ADAPTER    void   (*mem_free)( void *ptr);

    CIOT_ADAPTER    Ciot_res (* mutex_init) (void);
    CIOT_ADAPTER    Ciot_res (* mutex_delete) (void);
    CIOT_ADAPTER    Ciot_res (* mutex_lock) (void);
    CIOT_ADAPTER    Ciot_res (* mutex_unlock) (void);

    CIOT_ADAPTER    Ciot_res (* flash_read_license)( uint8_t * buf, uint32_t len );
    CIOT_ADAPTER    Ciot_res (* flash_save_license)( const uint8_t * buf, uint32_t len );

    CIOT_ADAPTER    Ciot_res (* flash_read_config)( uint8_t * buf, uint32_t len );
    CIOT_ADAPTER    Ciot_res (* flash_save_config)( const uint8_t * buf, uint32_t len );
    CIOT_ADAPTER    Ciot_res (* flash_erase_config)( const uint8_t * buf, uint32_t len );

    CIOT_ADAPTER    Ciot_time_ms (* get_system_ms)(void);
    CIOT_ADAPTER    Ciot_time_ms (* get_tick_count)(void);

    CIOT_ADAPTER    Ciot_res (*sync_time_ms) ( Ciot_time_ms timeStampInMS );

    CIOT_ADAPTER    uint64_t (*random_number)(void);

} ciot_system_adapter_manager;

extern Ciot_res ciot_porting_system_init();
extern int g_random_number;

#if USE_POSIX_SYSTEM
ciot_system_adapter_manager * ciot_system_adapter_posix();
#endif

CIOT_API
Ciot_res ciot_system_adapter_manager_reg( ciot_system_adapter_manager * sys_adapter );

CIOT_API
const ciot_system_adapter_manager * ciot_system_adapter_manager_instance();

#define ciot_sys_reg(A) ciot_system_adapter_manager_reg(A)
#define ciot_sys_mgr() ciot_system_adapter_manager_instance()
#define ciot_sys() ciot_sys_mgr()

// extern int g_random_number;

#ifdef __cplusplus
}
#endif

#endif //CIOT_SYSTEM_H
